/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.core.database;

import java.io.IOException;
import java.io.InputStream;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cred.industries.core.exceptions.ApplicationException;
import com.cred.industries.core.transferObj.result.ReturnCodes;


/**
 * defines for how to connect to the DB. In once place so it is easy to update.
 * This class is immutable.
 */
public class DBConfig {
	
	private static final String DB_POOL_MAX_CON_ELEMENT = "dbPoolMaxCon";

	private static final String DB_POOL_MIN_CON_ELEMENT = "dbPoolMinCon";

	private static final String URI_ELEMENT = "uri";

	private static final String PASSWORD_ELEMENT = "password";

	private static final String USER_ELEMENT = "user";

	private static final String DRIVER_NAME_ELEMENT = "driverName";

	private static final String SQL_ELEMENT = "sql";

	private static final Logger logger = LoggerFactory.getLogger(DBConfig.class);
	
	private static final String CONFIG_FILENAME = "dbconfig.xml";

    private String mDBDriverName;
    private String mDBUserName;
    private String mDBPassword;
    private String mDBURI;
    private int mDBPoolMinCon;
	private int mDBPoolMaxCon;
	
	/**
	 * 
	 * @return a url used to connect to the DB
	 */
	public String getConnectionUrl()	{
        
		return mDBURI + "?user=" + mDBUserName + "&password=" + mDBPassword;
	}

	/**
	 * constructor
	 */
    public DBConfig() {
    	
    	init();
    }
    
    /**
     * loads the db settings from a config file xml, then pulls out the needed values
     * if it is unable to load the config file it will leave the default values 
     */
    private void init() { 
        SAXBuilder builder = new SAXBuilder();


        try {
            ClassLoader cl = this.getClass().getClassLoader();
            
            try (InputStream inputStream = cl.getResourceAsStream(CONFIG_FILENAME)) {
            	
	            if(inputStream == null) {
	            
	            	//i am having issues with this not being found while running
	            	//under the test framework. So for now use defaults in that case.
	            	logger.error("unable to load dbconfig.xml, using defaults");
	            	return;
	            }
	
	            Document doc = builder.build(inputStream);
	            Element root = doc.getRootElement();
	            Element sqlRoot = root.getChild(SQL_ELEMENT);
	
	            mDBDriverName = sqlRoot.getChild(DRIVER_NAME_ELEMENT).getTextTrim();
	            mDBUserName = sqlRoot.getChild(USER_ELEMENT).getTextTrim();
	            mDBPassword = sqlRoot.getChild(PASSWORD_ELEMENT).getTextTrim();
	            mDBURI = sqlRoot.getChild(URI_ELEMENT).getTextTrim();
	            mDBPoolMinCon =  Integer.parseInt(sqlRoot.getChild(DB_POOL_MIN_CON_ELEMENT).getTextTrim());
	            mDBPoolMaxCon = Integer.parseInt(sqlRoot.getChild(DB_POOL_MAX_CON_ELEMENT).getTextTrim());
            }
            
       } catch (JDOMException e) {
          throw new ApplicationException(ReturnCodes.UNKNOWN_ERROR, "unable to build xml doc from " + CONFIG_FILENAME);
       } catch (IOException e) {
          throw new ApplicationException(ReturnCodes.UNKNOWN_ERROR, "unable to load xml doc from " + CONFIG_FILENAME);
       } 
    }

	public String getDBDriverName() {
		return mDBDriverName;
	}

	public String getDBUserName() {
		return mDBUserName;
	}

	public String getDBPassword() {
		return mDBPassword;
	}

	public String getDBURI() {
		return mDBURI;
	}

    public int getDBPoolMinCon() {
		return mDBPoolMinCon;
	}

	public int getDBPoolMaxCon() {
		return mDBPoolMaxCon;
	}

}
